<template>
  <div class="main-header">
      <div>
        <el-form :model="authorizationInformation" ref="authorizationInformation" label-width="40%">
          <el-row :gutter="24">
              <div style="margin-bottom: 20px;">
                <div style="margin-bottom: 10px;">
                    <span class="tip" style="width: 140px;display: inline-block;text-align: right;font-size: 14px;">设备ID：</span>
                    <el-input v-model="authorizationInformation.CorpUUID" style="width: 100%;" size="small" maxlength="12" oninput="value=value.replace(/[^0-9]/g,'')" ref="inputRef"
                     >
                        <!-- <el-button slot="append" icon="el-icon-check" @click="save" title="保存设备ID"></el-button> -->
                        <el-button slot="append" icon="el-icon-document-copy" @click="copy" title="复制设备ID"></el-button>
                    </el-input>
                </div>
                <div style="margin-bottom: 10px;">
                    <span class="tip" style="width: 140px;display: inline-block;text-align: right;font-size: 14px;">授权到期时间：</span>
                    <el-input v-model="authorizationInformation.ValidTime"  style="width:calc(100% - 300px);" size="small" disabled></el-input>
                    <span :style="{color: authorizationInformation.Days > 30 ? '#0ECB92' :  '#FD8854', fontSize: '14px', marginLeft: '10px'}">授权剩余{{ authorizationInformation.Days || 0 }}天</span>
                </div>
                <!-- <div style="margin-bottom: 10px;">
                    <span style="width: 40%;display: inline-block;text-align: right;font-size: 14px;">最多可以注册日志源数量：</span>
                    <el-input v-model="authorizationInformation.LicenseCount" style="width:calc(100% - 300px);" size="small" disabled></el-input>
                </div> -->
                <div  style="display:flex;align-item:center;margin-top:130px;justify-content: flex-end;margin-right:10px;">
                  <div>
                    <el-button  type="primary"  title="导入授权文件"  @click="save()">保存设备ID</el-button>
                  </div>
                  <span style="display: inline-block;text-align: right;margin-left:10px;">
                    <el-upload
                      class="upload-demo"
                      action
                      :ref="'uploads'+0"
                      :on-change="handleChange()"
                      :show-file-list = false
                      :http-request="upgradeClick"
                      :on-exceed="handleExceeds"
                      :limit="1">
                      <el-button  type="primary"  title="导入授权文件"  @click="beforeUploadClick(0,'导入授权文件')">导入授权文件</el-button>
                    </el-upload>
                  </span>
                </div>
            </div>
          </el-row>
        </el-form>    
      </div>
      <div>
      </div>
</div>
</template>

<script>
import { connrequest, uploadfile } from "@/api/firstPage"
import { parseTime } from "@/utils/index.js";
import { getToken } from '@/utils/auth' // get token from cookie
export default {
  data(){
    return{
      authorizationInformation: {},
      applicationCode: '',
      authorizationCode: '',
      color:''
    }
  },
  created(){
    this.getData();
  },
  mounted(){
    
  },
  methods:{
      // 获取邮件列表数据
      async getData(){
        const res = await connrequest('GetLicense');
        if (res.Status.StatusCode === 0) {
          this.authorizationInformation = {...res.Data, ValidTime: parseTime(res.Data.ValidTime * 1000), Days: this.calculateDateAfterNdays(res.Data.ValidTime) }
        }
      },
      // 剩余天数
      calculateDateAfterNdays(ValidTime) {
        // 当前时间戳
        let currentTimestamp = (new Date()).getTime() / 1000;
        // 计算时间差并转换成天数
        let difference = Math.floor((ValidTime - currentTimestamp) / (60 * 60 * 24));
        return difference
      },
      handleChange(row) {
        // console.log(row);
      },
      beforeUploadClick(index,val) {
        this.selectType = val
        this.slectIndex = index
      },
      handleExceeds(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      async save(){
        this.$confirm('此操作将会清除已有的授权信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const data = {
          Data:{
            UUID: this.authorizationInformation.CorpUUID
          }
        }
        const res = await connrequest('SetDeviceUUID', data)
        if(res.Status.StatusCode === 0) {
          this.$message.success('保存成功')
          this.getData()
        }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      },
      copy(){
        // 选择输入框中的内容
        this.$refs.inputRef.select();
        // 复制选定的文本到剪贴板
        document.execCommand('copy');
        // 取消选择文本
        window.getSelection().removeAllRanges();
        this.$message.success('复制成功')
      },
      async upgradeClick(file){
            // 导入授权文件
            const loading = this.$loading({
                lock: true,
                text: '导入授权文件中请稍后......',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            if (file.file.size > 102400000) {
                this.$refs['uploads'+this.slectIndex].clearFiles();
                setTimeout(() => {
                    loading.close();
                    this.$message.warning('文件大小不允许超过1KB');
                }, 1000);
            }else{
              let formData = new FormData();
              if (this.selectType === '导入授权文件') {
                var fileName = "param_license.cfg";
                // 创建一个新的Blob对象，将文件对象和文件名传入
                var newFile = new Blob([file.file], { type: file.file.type });
                newFile.name = fileName;
                formData.append('CmdCode', "UpdateLicense");
                formData.append('file', newFile, fileName);     
                  const res = await uploadfile(formData)
                  if(res.Status.StatusCode === 0) {
                    loading.close();
                    this.$message.success('更新授权信息成功')
                    this.$refs['uploads'+this.slectIndex].clearFiles();
                    this.getData();
                  }else{
                    this.$refs['uploads'+this.slectIndex].clearFiles();
                    setTimeout(() => {
                        loading.close();
                    },1000)  
                  }
                }
            }
        }
  }
}
</script>

<style lang="scss" scoped>
.text {
font-size: 14px;
}
.box-card{
// margin: 16px;
margin-bottom: 16px !important;
}
.cardHeard{
display: flex;
align-items: center;
justify-content: space-between;
}
::v-deep .el-input--small{
  width:40% !important;
}
::v-deep .el-card__header{
padding: 10px !important;
}
.el-form-item{
margin-bottom: 10px !important;
}
::v-deep .el-form-item__error{
padding-top:  0 !important;
}
.el-row{
  margin-left: 0 !important;
  margin-right: 0 !important;
}
.tip{
  color:#606266;
}
.night{
  .tip{
  color:#fff;
}
 .el-row{
  background: #363b4d !important;
  ::v-deep .el-input__inner{
     
      color: #fff !important;
      background-color: #2a2d3c !important;
      border: 1px solid #3f4456 !important;
  }
 }


}


 

</style>